<script lang="ts" setup>
import { transformFormSchema, useAddEditForm, useAddEditFormModal } from '#/hooks/useAddEditForm'
import { $t } from '@vben/locales'

import { getAddEditFormSchema } from '../data/AddEditFrom'
import { PAGE_NAME } from '../use/config'

defineOptions({
    name: 'FormModelMenu'
})

const props = withDefaults(
    defineProps<{
        modalType?: 'drawer' | 'modal'
    }>(),
    {
        modalType: 'modal'
    }
)

defineEmits(['success'])

const { Form, formApi, formTitle, setRowId, setViewMode } = useAddEditForm({
    title: PAGE_NAME,
    useFormParams: {
        wrapperClass: 'grid-cols-1 md:grid-cols-2 ',
        commonConfig: {
            labelWidth: 150
        }
    }
})

const { Modal, modalApi } = useAddEditFormModal({
    formApi,
    modalType: props.modalType,
    useModalParams: {
        class: 'w-[1000px]'
    },
    onOpen({ record, isViewMode = false }) {
        setViewMode(isViewMode)
        setRowId(record?.id ?? null)

        if (isViewMode) {
            modalApi.setState({
                showConfirmButton: false,
                cancelText: $t('common.close')
            })
        } else {
            modalApi.setState({
                showConfirmButton: true,
                cancelText: $t('common.cancel')
            })
        }
        const schema = getAddEditFormSchema()

        formApi.setState({
            // 更新表单数据
            schema: isViewMode ? transformFormSchema(schema) : schema
        })

        // 回填表单数据
        if (record) {
            formApi.setValues(record)
        }
    }
})
</script>
<template>
    <Modal :title="formTitle">
        <Form />
    </Modal>
</template>
